package vip.xiaonuo.core.filter;

import cn.hutool.core.collection.ListUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import vip.xiaonuo.common.pojo.CommonResult;

import java.io.IOException;
import java.util.List;

@Component
@WebFilter(filterName="HttpServletRequestReplacedFilter",urlPatterns="/*",value = "1")
public class HttpServletRequestReplacedFilter  implements Filter{
    // 设置排除路径
    private final List<String> excludeUrls = ListUtil.of("/swagger-ui/","/v3/api-docs","/swagger-resources/");

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }
    private boolean isExcludeUrls(String url){
        for(String excludeUrl : excludeUrls){
            if(url.startsWith(excludeUrl)){
                return true;
            }
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        if (isExcludeUrls(requestURI)) {
            //不做任何处理
            chain.doFilter(request, response);
        }else {
            try {
                ServletRequest requestWrapper = null;
                if (request instanceof HttpServletRequest) {
                    requestWrapper = new RequestReaderHttpServletRequestWrapper((HttpServletRequest) request);
                }
                //获取请求中的流如何，将取出来的字符串，再次转换成流，然后把它放入到新request对象中。
                // 在chain.doFiler方法中传递新的request对象
                if (requestWrapper == null) {
                    chain.doFilter(request, response);
                } else {
                    chain.doFilter(requestWrapper, response);
                }
            } catch (Exception e) {
                HttpServletResponse httpResp = (HttpServletResponse) response;
                httpResp.setStatus(200);
                httpResp.setContentType("application/json;charset=UTF-8");
                httpResp.getWriter().write(CommonResult.error(e.getMessage()).toString());
            }
        }
    }

    @Override
    public void destroy() {

    }
}

